<template>
  <view class="personal-page">
    <!-- 顶部背景 - 渐变颜色 -->
    <view class="top-bg"></view>

    <!-- 用户信息区域 -->
    <view class="user-info-section">
      <view class="avatar-container" @click="handleAvatarClick">
        <image :src="userInfo.avatarUrl || defaultAvatar" mode="widthFix" class="avatar"
          :alt="userInfo.nickname || '用户头像'">
        </image>
        <view class="login-indicator" v-if="!isLogin">
          <uni-icons type="plus" size="16" color="#fff"></uni-icons>
        </view>
      </view>

      <view class="user-info">
        <view class="user-name">{{ userInfo.nickname || '点击头像登录' }}</view>
        <view class="user-signature-container" @click="handleOutsideClick">
          <!-- 未登录状态：显示登录引导 -->
          <view class="user-desc login-guide" v-if="!isLogin" @click.stop="handleLoginClick">
            点击登录完善个人信息
          </view>

          <!-- 已登录但无签名：显示完善提示，可点击进入编辑 -->
          <view class="user-desc" v-else-if="isLogin && !userInfo.signature && !isEditingSignature"
            @click.stop="startEditing">
            完善个人信息，让更多人认识你
          </view>

          <!-- 已登录有签名：显示签名内容，可点击进入编辑 -->
          <view class="user-desc" v-else-if="isLogin && userInfo.signature && !isEditingSignature"
            @click.stop="startEditing">
            {{ userInfo.signature }}
          </view>

          <!-- 编辑状态：显示输入框 -->
          <input v-else-if="isLogin && isEditingSignature" class="signature-input" v-model="editingSignature"
            type="text"  placeholder="请输入个性签名" @blur="saveSignature" @click.stop auto-focus maxlength="30" 
          />
        </view>
      </view>
    </view>

    <!-- 功能列表 -->
    <view class="function-list">
      <!-- 我的内容 -->
      <view class="function-section">
        <view class="section-title">我的内容</view>
        <view class="function-items">
          <view class="function-item" @click="gotoMySurveys">
            <view class="item-icon">
              <uni-icons type="list" size="22" color="#ff9900"></uni-icons>
            </view>
            <view class="item-text">历史问卷</view>
            <view class="item-arrow">
              <uni-icons type="right" size="18" color="#ccc"></uni-icons>
            </view>
          </view>

          <view class="function-item" @click="gotoCollections">
            <view class="item-icon">
              <uni-icons type="star" size="22" color="#ff3366"></uni-icons>
            </view>
            <view class="item-text">我的收藏</view>
            <view class="item-arrow">
              <uni-icons type="right" size="18" color="#ccc"></uni-icons>
            </view>
          </view>
        </view>
      </view>

      <!-- 系统功能 -->
      <view class="function-section">
        <view class="section-title">系统功能</view>
        <view class="function-items">
          <view class="function-item" @click="gotoDiscussion">
            <view class="item-icon">
              <uni-icons type="chatbubble" size="22" color="#36d399"></uni-icons>
            </view>
            <view class="item-text">畅所欲言</view>
            <view class="item-arrow">
              <uni-icons type="right" size="18" color="#ccc"></uni-icons>
            </view>
          </view>

          <view class="function-item" @click="gotoAboutUs">
            <view class="item-icon">
              <uni-icons type="info" size="22" color="#722ed1"></uni-icons>
            </view>
            <view class="item-text">关于我们</view>
            <view class="item-arrow">
              <uni-icons type="right" size="18" color="#ccc"></uni-icons>
            </view>
          </view>

          <view class="function-item" @click="gotoContactUs">
            <view class="item-icon">
              <uni-icons type="phone" size="22" color="#f5222d"></uni-icons>
            </view>
            <view class="item-text">联系我们</view>
            <view class="item-arrow">
              <uni-icons type="right" size="18" color="#ccc"></uni-icons>
            </view>
          </view>
        </view>
      </view>

      <!-- 登录相关 -->
      <view class="function-section" v-if="isLogin">
        <view class="function-items">
          <view class="function-item danger" @click="showLogoutConfirm">
            <view class="item-icon">
              <uni-icons type="gear" size="22" color="#f5222d"></uni-icons>
            </view>
            <view class="item-text">退出登录</view>
            <view class="item-arrow">
              <uni-icons type="right" size="18" color="#ccc"></uni-icons>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 新增：获取用户信息确认弹窗 -->
    <uni-popup ref="userInfoPopup" type="dialog" :mask="true">
      <view class="popup-content">
        <view class="popup-title">获取用户信息</view>
        <view class="popup-message">需要获取您的头像和昵称，用于完善个人资料</view>
        <view class="popup-buttons">
          <button class="cancel-btn" @click="closeUserInfoPopup">暂不授权</button>
          <button class="confirm-btn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">选择头像</button>
        </view>
      </view>
    </uni-popup>

    <!-- 昵称输入弹窗 -->
    <uni-popup ref="nicknamePopup" type="dialog" :mask="true">
      <view class="popup-content">
        <view class="popup-title">设置昵称</view>
        <view class="popup-message">请输入您的昵称</view>
        <input type="nickname" class="nickname-input" placeholder="请输入昵称" @blur="onNicknameInput" />
        <view class="popup-buttons">
          <button class="cancel-btn" @click="closeNicknamePopup">取消</button>
          <button class="confirm-btn" @click="confirmNickname">确认</button>
        </view>
      </view>
    </uni-popup>

    <!-- 退出登录确认弹窗 -->
    <uni-popup ref="logoutPopup" type="dialog" :mask="true">
      <view class="popup-content">
        <view class="popup-title">确认退出登录？</view>
        <view class="popup-message">退出后需要重新登录才能使用相关功能</view>
        <view class="popup-buttons">
          <button class="cancel-btn" @click="closeLogoutPopup">取消</button>
          <button class="confirm-btn" @click="logout">确认退出</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 默认头像
      defaultAvatar: "https://picsum.photos/id/64/200/200",
      // 用户信息
      userInfo: {
        nickname: '',
        signature: '',
        // avatarUrl: "",
        // nickname: "",
        // signature: ""
      },
      // 登录状态
      isLogin: false,
      isEditingSignature: false,
      editingSignature: ''
    };
  },
  onLoad() {
    // 检查登录状态
    console.log(uni.getStorageSync('uid'))
    this.checkLoginStatus();
  },
  onShow() {
    // 页面显示时再次检查，确保状态同步
    this.checkLoginStatus();
  },
  methods: {
    // 检查登录状态
    checkLoginStatus() {
      // 从本地存储获取登录信息
      const isLogin = uni.getStorageSync('isLogin');
      const userInfo = uni.getStorageSync('userInfo');

      if (isLogin && userInfo && userInfo.avatarUrl) {
        this.userInfo = userInfo;
        this.isLogin = true;
      } else {
        this.userInfo = {};
        this.isLogin = false;
      }
    },

    // 头像点击事件 - 登录/查看大图
    handleAvatarClick() {
      if (!this.isLogin) {
        // 未登录 - 调用微信登录
        this.wechatLogin();
      } else {
        // 已登录 - 查看头像大图
        this.previewAvatar();
      }
    },
     // 开始编辑签名
    startEditing() {
      this.isEditingSignature = true;
      // 初始化编辑框内容（如果有旧签名）
      this.editingSignature = this.userInfo.signature || '';
    },

    // 保存签名
    saveSignature() {
      this.isEditingSignature = false;
      this.userInfo.signature = this.editingSignature;
      // 触发保存事件，将新签名传递给父组件
      // this.$emit('update-signature', this.editingSignature);
    },

    // 点击空白区域保存
    handleOutsideClick() {
      if (this.isEditingSignature) {
        this.saveSignature();
      }
    },

    // 微信登录
    wechatLogin() {
      // 显示加载提示
      uni.showLoading({
        title: '登录中...'
      });

      // 调用微信登录API
      uni.login({
        provider: 'weixin',
        success: (loginRes) => {
          // 提取code（确保code存在）
          const code = loginRes.code;
          if (!code) {
            uni.hideLoading();
            uni.showToast({
              title: '获取code失败',
              icon: 'none'
            });
            return;
          }

          // 将code发送到后端进行验证
          uni.request({
            url: 'https://wxapi.xiaoyiwl.cn/WechatLogin.php',
            method: 'GET',
            data: {
              code: code
            },
            success: (res) => {
              // console.log('后端登录验证结果', res.data);

              // 验证后端响应格式是否正确
              if (typeof res.data !== 'object') {
                uni.showToast({
                  title: '登录失败：响应格式错误',
                  icon: 'none'
                });
                return;
              }

              // 后端返回成功（code:200）
              if (res.data.code === 200 && res.data.data) {
                const { token, uid, expires_in } = res.data.data;

                // 存储登录状态（使用uni.setStorageSync持久化）
                uni.setStorageSync('isLogin', true);
                if (uid) uni.setStorageSync('uid', uid);
                if (token) {
                  uni.setStorageSync('token', token);
                  // 存储令牌过期时间（便于后续自动刷新）
                  const expireTime = new Date().getTime() + expires_in * 1000;
                  uni.setStorageSync('tokenExpireTime', expireTime);
                }

                // 登录成功后获取用户信息
                // 不直接获取用户 而是弹出询问框 让用户选择
                this.isLogin = true
                uni.hideLoading()
                this.$refs.userInfoPopup.open();

              } else {
                // 后端返回错误
                const errorMsg = res.data.message || '登录验证失败';
                console.log('后端登录验证失败', errorMsg);
                uni.showToast({
                  title: errorMsg,
                  icon: 'none'
                });
              }
            },
            fail: (err) => {
              console.log('请求后端登录接口失败', err);
              uni.showToast({
                title: '连接服务器失败',
                icon: 'none'
              });
            },
            complete: () => {
              // 隐藏加载提示
              uni.hideLoading();
            }
          });
        },
        fail: (err) => {
          console.log('微信登录失败', err);
          uni.hideLoading();
          uni.showToast({
            title: '登录失败，请重试',
            icon: 'none'
          });
        }
      });
    },
    // 关闭授权弹窗
    closeUserInfoPopup() {
      this.$refs.userInfoPopup.close();
      // 即使不授权，也显示默认信息
      this.userInfo = {
        avatarUrl: this.defaultAvatar,
        nickname: '微信用户'
      };
      uni.setStorageSync('userInfo', this.userInfo);
    },

    // 处理用户选择头像事件
    onChooseAvatar(e) {
      console.log(e)
      const { avatarUrl } = e.detail;
      if (avatarUrl) {
        // 更新头像
        this.userInfo.avatarUrl = avatarUrl;

        // 关闭头像选择弹窗
        this.$refs.userInfoPopup.close();

        // 打开昵称输入弹窗
        this.$nextTick(() => {
          this.$refs.nicknamePopup.open();
        });
      }
    },

    // 处理昵称输入
    onNicknameInput(e) {
      this.tempNickname = e.detail.value;
    },

    // 关闭昵称弹窗
    closeNicknamePopup() {
      this.$refs.nicknamePopup.close();
      // 使用默认昵称
      this.userInfo.nickname = '微信用户';
      this.saveUserInfo();
    },

    // 确认昵称
    confirmNickname() {
      if (this.tempNickname) {
        this.userInfo.nickname = this.tempNickname;
      } else {
        this.userInfo.nickname = '微信用户';
      }

      this.$refs.nicknamePopup.close();
      this.saveUserInfo();
    },

    // 保存用户信息
    saveUserInfo() {
      // 保存用户信息
      uni.setStorageSync('userInfo', this.userInfo);

      // 更新页面数据
      this.isLogin = true;

      // 提示用户
      uni.showToast({
        title: '设置成功',
        icon: 'success'
      });

      // 同步用户信息到后端
      this.syncUserInfoToBackend(this.userInfo);
    },

    /**
     * 将用户信息同步到后端数据库
     */
    syncUserInfoToBackend(userInfo) {
      const token = uni.getStorageSync('token');
      if (!token) return;

      uni.request({
        url: 'https://wxapi.xiaoyiwl.cn/syncUserInfo.php',
        method: 'POST',
        header: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        data: {
          avatarUrl: userInfo.avatarUrl,
          nickname: userInfo.nickname
        },
        success: (res) => {
          if (res.data.code !== 200) {
            console.log('用户信息同步失败', res.data.message || '未知错误');
          }
        },
        fail: (err) => {
          console.log('同步用户信息请求失败', err);
        }
      });
    },

    // 预览头像
    previewAvatar() {
      uni.previewImage({
        urls: [this.userInfo.avatarUrl || this.defaultAvatar],
        current: this.userInfo.avatarUrl || this.defaultAvatar
      });
    },

    // 显示退出登录确认
    showLogoutConfirm() {
      this.$refs.logoutPopup.open();
    },

    // 关闭退出登录确认
    closeLogoutPopup() {
      this.$refs.logoutPopup.close();
    },

    // 退出登录
    logout() {
      // 清除所有存储的用户信息
      this.userInfo = {};
      this.isLogin = false;
      uni.removeStorageSync('userInfo');
      uni.removeStorageSync('token');
      uni.removeStorageSync('uid');
      uni.removeStorageSync('isLogin');
      uni.removeStorageSync('tokenExpireTime');

      // 关闭弹窗
      this.closeLogoutPopup();

      // 提示
      uni.showToast({
        title: '已退出登录',
        icon: 'none'
      });
    },

    // 跳转至我的问卷
    gotoMySurveys() {
      this.checkLoginAndNavigate('../../myPackage/pages/my/history');
    },

    // 跳转至我的收藏
    gotoCollections() {
      this.checkLoginAndNavigate('/pages/mine/collections');
    },

    // 跳转至畅所欲言
    gotoDiscussion() {
      this.checkLoginAndNavigate('/pages/discussion');
    },

    // 跳转至关于我们
    gotoAboutUs() {
      uni.navigateTo({
        url: '/pages/mine/about'
      });
    },

    // 跳转至联系我们
    gotoContactUs() {
      uni.navigateTo({
        url: '/pages/mine/contact'
      });
    },

    // 检查登录状态并跳转
    checkLoginAndNavigate(url) {
      if (this.isLogin) {
        uni.navigateTo({
          url: url
        });
      } else {
        uni.showModal({
          title: '提示',
          content: '请先登录',
          confirmText: '去登录',
          success: (res) => {
            if (res.confirm) {
              this.handleAvatarClick();
            }
          }
        });
      }
    }
  }
};
</script>


<style scoped lang="scss">
.personal-page {
  background-color: #f5f5f7;
  min-height: 100vh;
  position: relative;
}

// 顶部背景 - 已修改为蓝紫渐变
.top-bg {
  width: 100%;
  height: 120px;
  // 新的渐变：从蓝紫色过渡到深蓝色
  background: linear-gradient(135deg, #6b63d8 0%, #3a7bd5 100%);
}

// 用户信息区域
.user-info-section {
  display: flex;
  align-items: flex-start;
  padding: 0 16px;
  position: absolute;
  top: 3.125rem;
  left: 0;
  right: 0;

  .avatar-container {
    position: relative;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    overflow: hidden;
    border: 4px solid #fff;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    background-color: #eee;

    .avatar {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .login-indicator {
      position: absolute;
      bottom: 0;
      right: 0;
      width: 30px;
      height: 30px;
      border-radius: 50%;
      background-color: #6b63d8;
      /* 与渐变颜色匹配 */
      display: flex;
      align-items: center;
      justify-content: center;
      border: 2px solid #fff;
    }
  }

  .user-info {
    margin-left: 16px;
    margin-top: 12px;
    flex: 1;

    .user-name {
      font-size: 18px;
      font-weight: 600;
      color: #fff;
      margin-bottom: 4px;
    }

    .user-desc {
      font-size: 14px;
      color: #fff;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }

    .signature-input {
      outline: none;
      font-size: 28rpx;
      color: #333;
      // border: 1px solid rgb(0,0,0,.5)
      border-radius: 8rpx;
      padding: 10rpx;
      min-height: 40rpx;
    }
  }
}

// 功能列表
.function-list {
  padding: 16px;
  margin-top: 1.875rem;

  .function-section {
    background-color: #fff;
    border-radius: 12px;
    margin-bottom: 16px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .section-title {
      font-size: 14px;
      color: #999;
      padding: 12px 16px;
      background-color: #f9f9f9;
      border-bottom: 1px solid #f5f5f5;
    }

    .function-items {
      .function-item {
        display: flex;
        align-items: center;
        padding: 14px 16px;
        border-bottom: 1px solid #f5f5f5;
        transition: background-color 0.2s ease;

        &:last-child {
          border-bottom: none;
        }

        &:active {
          background-color: #f9f9f9;
        }

        &.danger {
          .item-text {
            color: #f5222d;
          }
        }

        .item-icon {
          width: 36px;
          height: 36px;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 8px;
          background-color: rgba(107, 99, 216, 0.1);
          /* 与渐变颜色匹配 */
        }

        .item-text {
          flex: 1;
          margin-left: 16px;
          font-size: 16px;
          color: #333;
        }

        .item-arrow {
          color: #ccc;
        }
      }
    }
  }
}

.user-signature-container {
  padding: 16rpx 0;
}

.user-desc {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
  min-height: 40rpx;
}

.login-guide {
  color: #007aff;  /* 引导登录文字用高亮色 */
}

.signature-input {
  font-size: 28rpx;
  color: #333;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  padding: 10rpx 16rpx;
  min-height: 60rpx;
  width: 100%;
  box-sizing: border-box;
}

// 弹窗样式
.popup-content {
  background-color: #fff;
  border-radius: 16px;
  padding: 24px 16px;

  .popup-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    text-align: center;
    margin-bottom: 8px;
  }

  .popup-message {
    font-size: 14px;
    color: #666;
    text-align: center;
    margin-bottom: 16px;
    padding: 0 16px;
  }

  // 昵称输入框样式
  .nickname-input {
    width: 90%;
    height: 44px;
    border: 1px solid #e8e8e8;
    border-radius: 8px;
    padding: 0 12px;
    font-size: 16px;
    margin: 0 auto 20px;
    display: block;

    &:focus {
      border-color: #6b63d8;
      outline: none;
    }
  }

  .popup-buttons {
    display: flex;

    .cancel-btn,
    .confirm-btn {
      flex: 1;
      height: 44px;
      border-radius: 8px;
      font-size: 16px;
    }

    .cancel-btn {
      background-color: #f5f5f5;
      color: #333;
      margin-right: 8px;
    }

    .confirm-btn {
      background-color: #f5222d;
      color: #fff;
      margin-left: 8px;
    }
  }
}
</style>
